<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\model\goods;
use think\Model;
class GoodsGiftCode extends Model{

    /**
     * 统计指定条件
     * @param $id
     * @return int|string
     */
    public static function countCode($id){
        return self::whereCode($id)->count();
    }

    /**
     * 指定查询
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function selCodeZhi($id){
        return self::whereCode($id)->select();
    }

    /**
     * 条件查询所有数据
     * @param $where
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function selCode($where, $where2, $order = 'id asc'){
        $data = self::where($where)->where($where2)->order($order)->select();
        $count1 = self::where($where)->count();
        $count2 = self::where($where)->where($where2)->count();
        $count3 = $count1 - $count2;
        $list = [
            'data' => $data,
            'count' => [$count1, $count2, $count3],
        ];
        return $list;
    }

    /**
     * 指定条件
     * @param $id
     * @return $this
     */
    public static function whereCode($id){
        return self::group('stage')->where(['lid' => $id, 'status' => 0]);
    }

    /**
     * 事务添加code码
     * @param $whole
     * @param $num
     * @param $id
     */
    public static function trans($whole, $num, $id){
        // 启动事务
        self::startTrans();
        try{
            for ($i = 0; $i < $whole; $i++){ //循环添加出所有的核销码
                $dang = $i + 1; //当前的个数
                $qi = ceil(($dang)/$num); //计算出当前核销码期数
                $number = str_pad($id.$dang, 6, '0', STR_PAD_LEFT); //前面补零
                $add = [
                    'lid' => $id,
                    'stage' => $qi,
                    'pi' => 1,
                    'number' => $number,
                    'status' => 0
                ];
                $insert = self::insert($add);
                if (!$insert) {
                    throw new \Exception("添加第".$dang."条数据失败");
                }
            }
            // 提交事务
            self::commit();
        } catch (\Exception $e) {
            // 回滚事务
            self::rollback();
        }
    }

    /**
     * 根据条件查询指定的一条数据
     * @param $where
     * @param string $field
     * @return array|false|\PDOStatement|string|Model
     */
    public static function getCodeInfo($where, $field = ''){
        return self::where($where)->field($field)->find();
    }

    /**
     * 根据条件修改数据
     * @param $where
     * @param $data
     * @return $this
     */
    public static function upCode($where, $data){
        return self::where($where)->update($data);
    }
}